package com.dd.stack.redis.service.inner.impl;

import com.dd.stack.redis.config.redisConfig.RedisKeyFactory;
import com.dd.stack.redis.pojo.DO.ProductDO;
import com.dd.stack.redis.service.inner.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/1/30 15:35
 * @Description Redis缓存实现
 */
@Slf4j
@Service
public class RedisCacheServiceImpl implements CacheService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void cacheProduct(ProductDO p) {
        // 设置存储时间 避免长期存储
        redisTemplate.opsForValue().set(RedisKeyFactory.singleProductKey(p.getId()), p, 10, TimeUnit.MINUTES);
    }

    @Override
    public ProductDO getProductFromCache(Long id) {
        ProductDO productDO = (ProductDO) redisTemplate.opsForValue().get(RedisKeyFactory.singleProductKey(id));
        if (productDO != null) {
            log.info("Product cache hit..");
        } else {
            log.info("Product cache miss..");
        }
        return productDO;
    }
}
